<?php

namespace Plu\qdh\Services;

use Httpful\Request;
use Plu\qdh\Services\ServiceBase;
use Plu\qdh\Models\App\Project;
use Plu\qdh\Models\App\Platform;
use Plu\qdh\Models\App\Product;
use Plu\qdh\Models\App\Auth;
use Plu\qdh\Plugins\WechatCryptPlugin;

class PassportService extends ServiceBase {

    const WECHAT_LOGIN = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';

    const USER_SESSION = "u:session:%s";

    const USER_3RDSESSION = "u:3rdsession:%s";

    const ADMIN_SESSION = "admin:session:%s";

    private $_userOpenId;

    public function isAdminLogin() {
        if ($this->cookies->has('qdhAdmin')) {
            $cookie = $this->cookies->get('qdhAdmin');
            $redis  = $this->getRedis('qdh');
            $key    = sprintf(self::ADMIN_SESSION, $cookie);
            if ($redis->get($key)) {
                return true;
            }
            return false;
        }
        return false;
    }


    public function adminLogin($username, $pswd) {
        $pswd  = md5($pswd);
        $login = Auth::checkUserPswd($username, $pswd);
        if ($login) {
            $sessionId = $this->generateNum();
            $redis     = $this->getRedis('qdh');
            $key       = sprintf(self::ADMIN_SESSION, $sessionId);
            $redis->set($key, $sessionId);
            $redis->eXpire($key, 15* 86400);
            $this->cookies->set('qdhAdmin',$sessionId,time()+ 15* 86400);
            return true;
        }
        return false;
    }

    public function isLogin() {
        $token = $this->request->getQuery('qdhtoken');
        if (empty($token)) {
             return 0;
        }
         $userData = $this->getUserSession($token);
         if (!$userData) {
             return 0;
         }
	    $userData = json_decode($userData, true);
	    $userId   = $userData['openid'];
        $this->_userOpenId = $userId;
        return $userId;
    }

    public function getUserId() {
        return $this->_userOpenId;
    }

    public function getUserSession($token) {
        $redis = $this->getRedis('qdh');
        $redisKey = sprintf(self::USER_SESSION, $token);
        return $redis->get($redisKey);
    }

    public function setUserSession($token, $data) {
        $redis = $this->getRedis('qdh');
        $redisKey = sprintf(self::USER_SESSION, $token);
        $redis->set($redisKey, $data);
        $redis->eXpire($redisKey, 86400);
    }

    // 微信授权
    public function loginWechat($code) {
        $sessionId  = $this->generateNum();
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
	    $requestUrl   = sprintf($url, \Wechat::APPID,  \Wechat::SECRET_KEY, $code);
	    $request      = Request::get($requestUrl)->send();
	    $responseBody = json_decode($request->body, true);
	    if ($responseBody['errcode']) {
            return [
                'code' => $responseBody['errcode'],
                'sessionId' => ''
            ];
        }
        $userData   = [
            'session_key' => $responseBody['session_key'],
            'openid'      => $responseBody['openid']
        ];

        $sessionId  = $this->generateNum();
        $redis = $this->getRedis('qdh');
        $userData = json_encode($userData);
        $this->setUserSession($sessionId, $userData);
        
        return [
            'code' => 200,
            'qdhtoken' => $sessionId
        ];

    }

    // 微信解密
    public function wechatCrypt($encryptedData, $iv, $sessionId) {

        $redis      = $this->getRedis('qdh');
        $redisKey   = sprintf(self::USER_3RDSESSION, $sessionId);
        $sessionKey = $redis->get($redisKey);

        if ($sessionKey) {
            $userData = null;
            $wechatPlugin = new WechatCryptPlugin(\Wechat::APPID, $sessionKey);
            $err = $wechatPlugin->decryptData($encryptedData, $iv, $userData);
            if ($err == \ErrorCode::$OK) {
                $qdhToken = $this->generateNum();
                $this->setUserSession($qdhToken, $userData);
                return [
                    'code' => 200,
                    'msg'  => 'success',
                    'qdhtoken' => $qdhToken,
                ];
            }
            return [
                'code' => $err,
                'msg'  => '授权失败'
            ];
        }
        return [
            'code' => 406,
            'msg'  => 'sessionId不可用或已过期'
        ];
    }

    private static function generateNum() {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $uuid   = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid,12, 4).substr($charid,16, 4).substr($charid,20,12);
        return $uuid;
    }






}
